//合同列表
var $customerContractTable = $('#customerContractTableList');
var endContractTime='',customerIdNum=''
//防止表头与表格不对齐
$(window).resize(function () {
    $customerContractTable.bootstrapTable('resetView');
});
var htmlIcon=`<span class="caret css-mdi"></span>`
// var htmlIcon=`<span class="mdi mdi-filter-outline css-mdi"></span>`
rowsList=[]

//初始化操作
$(function () {
    //高级筛选日期--配置参数
    $('.date-input').datepicker({
        language: "zh-CN",
        autoClose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });
    $('.create-time').datepicker({
        language: "zh-CN",
        autoClose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    })

    /*
    * 功能：模态框关闭重置表单内容
    * */
    $('.modal').on('hidden.bs.modal', function () {
        // 双重弹窗隐藏body滚动条
        if ($('.modal-backdrop').length) {
            $('body').addClass('modal-open');
        }
    })
    $('#addProductModal').on('hidden.bs.modal', function () {
        $('#paymentMethod').selectpicker('val', '');
        $('#addProductModal input:not([type="radio"]), #addProductModal textarea').val('');
        $('input[name="applyElectronicContract"][value="0"]').prop('checked', true);
        $('#addProductModal .surcharge-remarks, #addProductModal .approval').hide();
        $('.amount-total p').html('0');
    }).on('show.bs.modal', function () {
        $('#paymentMethod').selectpicker();
    });

    //初始化合同列表
    customerContractTableListInit();

    // 重置
    $('#btn-reset').on('click', function () {
        $('#btn-search-simple').prev('input').val('');
        resetSearch.call(this, customerContractTableListInit);
    });

    // 高级搜索
    function check(startTime,endTime){
        if(startTime.length>0 && endTime.length>0){
            var startTmp=startTime.split("-");
            var endTmp=endTime.split("-");
            var sd=new Date(startTmp[0],startTmp[1],startTmp[2]);
            var ed=new Date(endTmp[0],endTmp[1],endTmp[2]);
            if(sd.getTime()>ed.getTime()){
                $.alert('合同截止日期不能小于起始日期');
                return false;
            }
        }
        return true;
    }

    function checkTM(startTime,endTime){
        if(startTime.length>0 && endTime.length>0){
            var startTmp=startTime.split("-");
            var endTmp=endTime.split("-");
            var sd=new Date(startTmp[0],startTmp[1],startTmp[2]);
            var ed=new Date(endTmp[0],endTmp[1],endTmp[2]);
            if(sd.getTime()>ed.getTime()){
                $.alert('创建截止日期不能小于创建起始日期');
                return false;
            }
        }
        return true;
    }
    $('#btn-search').on('click', function () {
        if(Number($('#contractTotalAmountEnd').val())<Number($('#contractTotalAmountStart').val())){
            $.alert('合同截止金额不能小于起始金额');
        }else{
            check($("#contractStartDate").val(),$("#contractEndDate").val())
            checkTM($("#createTmStart").val(),$("#createTmEnd").val())
        }
        search($customerContractTable, advancedQueryParams);


    });
    $('#contractStatusSelectMultiple').multiselect({
        includeSelectAllOption: true,//设置为true或false以启用或禁用全选选项。
        selectAllText:" 全部",//全选选项显示的文本
        buttonText: function() {
            return '合同状态';
        },//指定按钮上显示的文本
        onDropdownShow: function (t) {//下拉菜单时调用的回调
            $('#contractStatusSelectMultiple').multiselect('deselectAll', false);
            $('#contractStatusSelectMultiple').multiselect('updateButtonText');
        },
        onDropdownHide: function (t) {//下拉菜单关闭后调用的回调。
            $('#contractStatusSelectMultiple').multiselect('deselectAll', false);
            $('#contractStatusSelectMultiple').multiselect('updateButtonText');
        },
    });

    // 上传图片
    $(document).on('click', '.file-browser', function () {
        var file = $(this).closest('.file-group').find('[type="file"]');
        var fileID = file.attr('id');
        var showID = file.nextAll('.img-box').attr('id');
        file.on('click', function (e) {
            e.stopPropagation();
            uploadPreview({
                fileID,
                showID
            });
        }).on('change', function () {
            file.trigger('click');
        })
        file.trigger('click');
    });
    // 解决table中点击行选中与checkbox冲突问题
    $('table').on('load-success.bs.table', function (e,data) {
        $(e.target).find('label.lyear-checkbox').on('click', function (e) {
            var $this = $(this);


            rowsList=[]
            totalAmountData=0,discountAmountData=0,realAmountData=0,receivablesData=0

            setTimeout(function () {
                $("#productListTable tbody  td input[type=text]").attr("disabled",false)
                $("#productListTable tbody .selected td input[type=text]").attr("disabled",true)

                rowsList = $('#productListTable').bootstrapTable('getSelections');

                //productDiscountPrice
                commitList(rowsList)
                for(let i=0,len=rowsList.length;i<len;i++){
                    if(rowsList[i].productDiscountPrice==''){
                        $.alert('报价不能为空！')
                        return false;
                    }
                }
                // 优惠券按钮开关
                if (rowsList.length == 1) {
                    $('#valuationTotal').val(rowsList[0].productDiscountPrice * rowsList[0].productNumber);
                    $('#couponTableToolbar button').prop('disabled', false);
                } else {
                    $('#valuationTotal').val('');
                    $('#couponTableToolbar button').prop('disabled', true);
                    $('#couponTable').bootstrapTable('removeAll');
                }
            },100)

            e.stopPropagation();
        })
    });

    // 起止日期
    timeData('contractDate');

    // 初始化合作开发人员列表
    cooperateTable();
    // 初始化合作开发人员列表-分公司下拉菜单
    companiesList();
    $('#accountList').selectpicker();



    // 优惠券弹窗相关功能
    $('#addCouponModal').on('show.bs.modal', function () {
        $('#couponCategories label:first-child input').prop('checked', true);
        couponTable(true);
    }).on('click', '#couponSearch', function () {
        search.call(this, $('#couponListTable'), couponQueryParams);
    }).on('click', '#couponCategories input', function () {
        $('#searchCouponName').val('');
        $(this).val() == '1' ? couponTable(true) : couponTable(false, 'checkbox');
    });


});

/**
 * 功能：合作开发人员列表初始化
 * */
function cooperateTable() {
    $('#cooperateTable').bootstrapTable({
        class: 'table table-bordered table-hover table-striped',
        striped: true,                  // 是否显示行间隔色
        sortable: true,                 // 是否启用排序
        pagination: false,              // 是否显示分页
        minimumCountColumns: 2,         // 最少要显示的列数
        undefinedText: '-',             // cell没有值时显示
        uniqueId: 'userId',
        toolbar: '#cooperateTableToolbar',
        columns: [
            {title: '主键', field: 'userId', visible: false},
            {title: '主键', field: 'companyId', visible: false},
            {title: '合作开发人员姓名', field: 'userName', align: 'left', valign: 'middle'},
            {title: '分配金额', field: 'allocationMount',align: 'left', valign: 'middle',
                events: {
                    'change input': function (e, value, row, index) {
                        var inputValue = $($(e.target)[0]).val().replace(/^\D*(\d*(?:\.\d{0,4})?).*$/g, '$1');
                        inputValue = Number(inputValue);
                        if (inputValue == 0) {
                            promptInfo('分配金额必须大于零，请重新输入！', function () {
                                $($(e.target)[0]).val('');
                            });
                            return;
                        }
                        $($(e.target)[0]).val(inputValue);
                        // 输入新值，先清空当前分配金额
                        row.allocationMount = '';
                        // 计算总计分配金额是否超过合同实际总金额
                        var flag = cooperateAmount(inputValue);
                        if (flag) {
                            // 未超过直接赋值
                            row.allocationMount = inputValue;
                        } else {
                            promptInfo('分配金额总和不能大于合同实际总金额，请重新输入！', function () {
                                $($(e.target)[0]).val('');
                                row.allocationMount = '';
                            });
                        }
                    }
                },
                formatter: function (value, row, index) {
                    var html = '<input type="text" class="form-control" value="' + (value || '') + '" id="allOcation-' + index + '" style="width: 200px;">';
                    return html;
                }
            },
            {title: '操作', field: 'couponDiscount', align: 'right', valign: 'middle', width: '120',
                formatter: function (value, row, index) {
                    var html = '<button type="button" class="btn btn-default btn-danger" onclick="removeRow(this, \'' + row.userId + '\')"><i class="mdi mdi-delete"></i>删除</button>';
                    return html;
                }
            },
        ],
        onPostBody: function (data) {
            // priceTotal();
            console.log(data)
        },
    });
}

/**
 * 功能：初始化分公司列表
 * 接口：罗杰
 * */
function companiesList() {
    $.ajax({
        url: '/sysCompany/selectCompanies',
        type: 'GET',
        dataType: "json",
        success: (function (data) {
            if (data.code == "000000") {
                var dataList = data.data;
                var selectOption = '';
                for (let i = 0; i < dataList.length; i++) {
                    selectOption += '<option value="' + dataList[i].companyId + '">' + dataList[i].companyName + '</option>';
                }
                $('#companiesList').selectpicker('destroy');
                $('#companiesList').html(selectOption).selectpicker({
                    size: 10
                });
            }
        }),
        error: (function (res) {
            $.alert({
                title: '错误提醒',
                content: '分公司列表数据请求失败'
            });
        })
    })
}

/**
 * 功能：根据所选分公司初始化人员列表
 * */
function getAccountList(element) {
    $('#addCooperateBtn').prop('disabled', true);

    var companyId = $(element).val();
    $.ajax({
        url: '/account/getAccountListByCompanyId',
        type: 'GET',
        dataType: "json",
        data: {
            companyId
        },
        success: (function (data) {
            if (data.code == "000000") {
                var dataList = data.data;
                var selectOption = '';
                for (let i = 0; i < dataList.length; i++) {
                    selectOption += '<option value="' + dataList[i].accountId + '">' + dataList[i].userName + '</option>';
                }
                $('#accountList').selectpicker('destroy').html(selectOption).prop('disabled', false).selectpicker({
                    size: 10
                }).one('changed.bs.select', function (event, clickedIndex, isSelected, previousValue) {
                    $('#addCooperateBtn').prop('disabled', false);
                })
            }
        }),
        error: (function (res) {
            $.alert({
                title: '错误提醒',
                content: '分公司人员数据请求失败'
            });
        })
    });
}

/**
 * 功能：新增合作开发人员
 * */
function addCooperate() {
    var companyId = $('#companiesList').val();
    var userId = $('#accountList').val();
    var userName = $('#accountList option:selected').html();

    var rowData = {
        companyId,              // 分公司Id
        userId,                 // 合作开发人员Id
        userName,               // 合作开发人员姓名
        allocationMount: ''     // 分配额度
    };

    var tableData = $('#cooperateTable').bootstrapTable('getData', true);

    if (tableData.length == 0) {
        // 直接插入
        $('#cooperateTable').bootstrapTable('append', rowData);
    } else {
        var flag = true;
        for (let i = 0; i < tableData.length; i++) {
            if (tableData[i].userId == userId) {
                flag = false;
                break;
            }
        }
        if (flag) {
            // 无重复，直接插入
            $('#cooperateTable').bootstrapTable('append', rowData);
        } else {
            // 提示有重复
            promptInfo('列表中已存在该联系人，不能重复添加！');
        }
    }
}

/**
 * 功能：分配金额计算，总计不能大于合同实际总金额
 * */
function cooperateAmount(amount) {
    // 输入值
    var amount = Number(amount);
    // 合同实际总金额
    var total = Number($('#realAmount').html());
    // 合作开发人员列表数据
    var tableData = $('#cooperateTable').bootstrapTable('getData', true);
    var tableDataTotal = 0;
    for (let i = 0; i < tableData.length; i++) {
        tableDataTotal += Number(tableData[i].allocationMount);
    }
    console.log('输入值：' + amount, '表格内已有值：' + tableDataTotal, '输入的总值：' + (amount + tableDataTotal), '合同实际金额：' + total);
    if (tableDataTotal + amount > total) {
        return false;
    } else {
        return true;
    }
}

/**
 * 功能：删除行
 * 参数：fieldId - 删除行的目标列字段名称  value - 目标字段值
 * */
function removeRow(_this, fieldId) {
    $(_this).parents('table').bootstrapTable('removeByUniqueId', fieldId);
}

$('#surcharge').on('change', function () {
    if ($(this).val() == '' || $(this).val() == '0') {
        $('.surcharge-remarks').hide();
    } else {
        $('.surcharge-remarks').show();
    }

    rowsList = $('#productListTable').bootstrapTable('getSelections');
    totalAmountData=0,discountAmountData=0,realAmountData=0,receivablesData=0
    if(rowsList.length==0){

        $("#totalAmount").html(totalAmountData)

        //    合同优惠总金额

        $("#discountAmount").html(discountAmountData)
        //    合同实际总金额 realAmount
        $("#realAmount").html(realAmountData)
        //    应收款 receivables
        $("#receivables").html(receivablesData)
    }

    commitList(rowsList);

    return;
    for(let i=0,len=rowsList.length;i<len;i++){
        //    合同总金额 totalAmountData
        if(rowsList[i].productMemberPrice!=''){
            totalAmountData+=rowsList[i].productMemberPrice* rowsList[i].productNumber
        }else{
            totalAmountData+=0
        }
        $("#totalAmount").html(totalAmountData)

        //    合同优惠总金额
        //    discountAmount
        if(rowsList[i].productDiscountPrice!=''){
            discountAmountData+=rowsList[i].productDiscountPrice* rowsList[i].productNumber
        }else{
            discountAmountData+=0
        }

        //    合同实际总金额 realAmount
        realAmountData=totalAmountData-discountAmountData

        $("#discountAmount").html(realAmountData)
        $("#realAmount").html(discountAmountData)
        //    应收款 receivables
        receivablesData=totalAmountData-realAmountData+Number($("#surcharge").val())
        $("#receivables").html(receivablesData)
    }
})

/**
 * 用户系统(普通用户)--合同列表
 */
function customerContractTableListInit() {
    //先销毁表格
    $customerContractTable.bootstrapTable('destroy');
    $customerContractTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/customerContract/selectCustomerContractList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'contractId',
        idField: 'contractId',
        pageSize: globalPageSize,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: globalPageList,//可供选择的每页的行数

        fixedColumns: true,     // 冻结列
        fixedNumber: 3,         // 左侧固定列
        fixedRightNumber: 1,    // 右侧固定列

        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'contractId', visible: false},
            {title: '订单ID', field: 'orderId', visible: false},
            {title: '客户Id', field: 'customerId', visible: false},
            {title: '是否是会员合同', field: 'whetherCheck', visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '52', formatter: indexFormat},
            {title: '合同编号' ,field: 'contractNumber',align: 'left', valign: 'middle', width: '120', class: 'ellipsis'},
            {title: '客户名称', field: 'customerName',align: 'left', valign: 'middle',formatter: customerNameFormat},
            {title: '联系人', field: 'contactName',align: 'left', valign: 'middle',formatter: contactNameFormat},
            /*{title: '合同类型', field: 'contractType',align: 'left', valign: 'middle'},*/
            {title: '合同状态', field: 'contractStatus',align: 'left', valign: 'middle',formatter: contractStatusFormat}, //contractStatus contractStatusMultiple
            {title: '联系方式', field: 'contactDetails',align: 'center', valign: 'middle',visible: false},
            {title: '客户邮箱', field: 'customerEmail',align: 'left', valign: 'middle',visible: false},
            {title: '创建日期', field: 'createTm', sortable: true, align: 'left', width: '120', valign: 'middle',visible: false},
            {title: '合同开始日期', field: 'contractStartDate',align: 'left', valign: 'middle',visible: false},
            {title: '合同结束日期', field: 'contractEndDate',align: 'left', valign: 'middle',visible: false},
            {title: '合同总金额', field: 'contractTotalAmount',align: 'left', valign: 'middle',visible: false},
            {title: '合同优惠总金额', field: 'contractDiscountTotalAmount',align: 'left', valign: 'middle',visible: false},
            {title: '合同实际总金额', field: 'contractActualTotalAmount',align: 'left', valign: 'middle',visible: false},
            {title: '合同应收款', field: 'contractReceivables',align: 'left', valign: 'middle',visible: false},
            {title: '合同总回款金额', field: 'contractTotalPaymentAmount',align: 'left', valign: 'middle',visible: false},
            {title: '合同审核状态', field: 'contractReviewStatus',align: 'left', valign: 'middle',visible: false,formatter: contractReviewStatus},
            {title: '审核人', field: 'reviewerName',align: 'left', valign: 'middle',visible: false},
            {title: '审核时间', field: 'reviewTime',align: 'left', valign: 'middle',visible: false},
            {title: '回款状态', field: 'paymentStatus',align: 'left', valign: 'middle',visible: false,formatter: paymentStatus},
            {title: '付款账号', field: 'paymentAccount',align: 'left', valign: 'middle',visible: false},
            {title: '是否保密', field: 'whetherKeepSecret',align: 'left', valign: 'middle',visible: false},
            {title: '提成发放状态', field: 'commissionStatus',align: 'left', valign: 'middle',visible: false},
            {title: '更新人', field: 'updatePeopleName',align: 'left', valign: 'middle',visible: false},
            {title: '更新日期', field: 'updateTm', sortable: true, align: 'left', valign: 'middle',visible: false},
            {title: '操作',field: 'operateFlag',align: 'right', width: '120', events: operateEvents, formatter: genderOpt},
        ],
        responseHandler: function (result) {
            // $customerContractTable.find('th[data-field="contractStatus"]').remove(htmlIcon)
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
                //,top:cssLeftY
                //contractStatusMultiple
                if($customerContractTable.find('.caret').length<1){
                    $customerContractTable.find('th[data-field="contractStatus"]').append(htmlIcon)
                }

                setTimeout(function () {
                    let cssLeftX=$(".css-mdi").offset().left-10+'px';
                    let cssLeftY=$(".css-mdi").offset().top-10+'px';
                    $(".select-absolute").css({position:"fixed",left: cssLeftX,top:cssLeftY})
                },100)




            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            $("[data-toggle='tooltip']").tooltip();
            // table操作列下拉菜单效果
            tableNav();
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });


}

/**
 * 合同状态
 */
function contractStatusFormat(value, row, index) {
    var spanImg;
    if (value == null || value == undefined) {
        return "-";
    }else{
        switch (value) {
            case "生效中":
                spanImg="<span class='img-all force-icon' title='' data-toggle='tooltip'>生效中</span>"
                break;
            case "未生效":
                spanImg="<span class='img-all no-force-icon' title='' data-toggle='tooltip'>未生效</span>"
                break;
            case "已结束":
                spanImg="<span class='img-all over-icon' title='' data-toggle='tooltip'>已结束</span>"
                break;
            case "已作废":
                spanImg="<span class='img-all invalid-icon' title='' data-toggle='tooltip'>已作废</span>"
                break;
            case "意外终止":
                spanImg="<span class='img-all accident-icon' title='' data-toggle='tooltip'>意外终止</span>"
                break;

        }
        return spanImg
    }

    // else if (1 == value) {
    //     //bg-success mdi mdi-15px mdi-checkbox-marked-outline
    //     return "<span class='img-all grant-img' title='已全部发放' data-toggle='tooltip'>已发放</span>";
    //     // return "<span class='img-all grant-img' title='已全部发放' data-toggle='tooltip'><img src='/images/mdiImg/grantImg.png' alt=''></span>已发放";
    // } else if (2 == value) {
    //     //bg-info mdi mdi-15px mdi-brightness-3
    //     return "<span class='img-all partial-img' title='部分发放' data-toggle='tooltip'>部分发放</span>";
    // } else if (3 == value){
    //     //bg-danger mdi mdi-15px mdi-close <img src='/images/mdiImg/unissuedImg.png' alt=''>
    //     return "<span class='img-all unissued-img' title='未发放' data-toggle='tooltip'>未发放</span>";
    // }
}

/**
 * 合同列表--(初始化页面)查询条件参数
 */
function queryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    params.dataType = $('#tabNumber').val();//tab页
    return params;
}

/**
 * 合同列表--搜索条件查询参数
 */
function advancedQueryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    //单选按钮
    params.dataType = $('#tabNumber').val();//tab页
    params.contractReviewStatus = $("input[name='reviewStatus']:checked").val();//审核状态

    // if($("input[name='reviewStatus']:checked").val()==''){
    //     $('#paymentStatusAll').prop('checked',true);
    // }
    params.paymentStatus = $("input[name='paymentStatus']:checked").val();//回款状态
    params.contractType = $("input[name='contractType']:checked").val();//合同类型

    params.dateType = $('#dateType').val();//dateType(all:全部; lastMonth:上月;thisWeek:本周; thisMonth:本月; thisYear:本年)

    params.customerName =  $.trim($('#customerName').val());  //客户名称
    params.contactName = $.trim($('#contactName').val());//联系人
    params.contractNumber = $.trim($('#contractNumber').val());//合同编号
    params.contractTotalAmountStart = $('#contractTotalAmountStart').val();//合同金额起始价
    params.contractTotalAmountEnd = $('#contractTotalAmountEnd').val();//合同金额截止价
    // if($('#contractTotalAmountEnd').val()<$('#contractTotalAmountStart').val()){
    //     $.alert('合同截止金额太小');
    // }

    // params.specialApprovalStatus = $('#approvalStatusSelect option:selected').val();//是否特批
    params.specialApprovalStatus = $("input[name='approvalStatusSelect']:checked").val();//合同类型
    //合同状态
    params.contractStatus = $("input[name='contractStatusRadio']:checked").val();//合同状态


    params.applyElectronicContract = $('#electronicContractSelect option:selected').val();//是否申请电子合同
    params.contractStartDate = $('#contractStartDate').val();//合同开始日期(有效期)
    params.contractEndDate = $('#contractEndDate').val(); //合同结束日期(有效期)

    params.createTmStart = $('#createTmStart').val();  //合同创建开始日期
    params.createTmEnd = $('#createTmEnd').val();    //合同创建截止日期
    params.contractStatusMultiple = JSON.stringify($('#contractStatusSelectMultiple').val());//合同状态(可多选)
    params.contractType = $("input[name='contractType']:checked").val();//(会员产品合同按合同类型查询会员新单合同、会员续费合同)合同类型

    return params;
}

/**
 * 合同列表--列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

/**
 * 合同列表--合同审核状态
 */
function contractReviewStatus(value, row, index) {
    if(row.contractReviewStatus=='0'){
        return "未审核";
    }else if(row.contractReviewStatus=='1'){
        return "审核中";
    }else if(row.contractReviewStatus=='2'){
        return "审核通过"
    }else if(row.contractReviewStatus=='3'){
        return "审核失败"
    }else if(row.contractReviewStatus=='4'){
        return "审核通过并盖章"
    }
}

/**
 * 点击客户姓名跳转客户详情页面
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function customerNameFormat(value, row, index) {
    if(value == null) {
        return '<span href="JavaScript:void(0);">-</span>';
    }else {
        return '<a href="JavaScript:void(0);" onclick=\'customerDetail(\"'+row.customerId+'")\'>'+value+'</a>';
    }

}

function  customerDetail(customerId) {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '客户详情',
        url: "/front/user/customerManager/customerDetail?customerId=" + customerId
    },true);
}

/**
 * 点击联系人姓名跳转联系人详情页面
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function contactNameFormat(value, row, index) {
    if(!value) {
        return '-';
    }
    return '<a href="JavaScript:void(0);"   onclick=\'contactDetail(\"'+row.contactName+'",\"'+row.contactDetails+'",\"'+row.customerId+'")\'>'+value+'</a>';
}

function  contactDetail(contactName,contactInformation,customerId) {
    var contactId = "";

    //查询联系人id,进行跳转
    $.ajax({
        url: '/contact/getContactId',
        type: 'POST',
        dataType: "json",
        data: {
            customerId: customerId,
            contactInformation : contactInformation,
            contactName : contactName
        },
        success: (function (data) {
            if (data.code == "000000") {
                if (data.data.contactId != null) {
                    contactId = data.data.contactId;
                    parent.$(parent.document).data('multitabs').create({
                        iframe: true,
                        title: '联系人详情',
                        url: "/front/user/contactManager/contactDetail?contactId=" + contactId
                    },true);
                }
            } else {
                alert("操作失败");
            }
        }),
        error: (function () {
            alert("失败");
        })
    });

}
/**
 * 合同列表--回款状态
 */
function paymentStatus(value, row, index) {
    if(row.paymentStatus=='0'){
        return "未回款";
    }else if(row.paymentStatus=='1'){
        return "已回款";
    }else if(row.paymentStatus=='3'){
        return "部分回款"
    }
}

/**
 * 合同列表--自定义操作列内容
 */
function genderOpt(value, row, index) {
    let day1 = new Date(row.contractEndDate);
    let day2 = new Date();
    let html = '';
    if(row.contractOtherType==1){
        html += '<button class="btn btn-default" id="paydetail"><i class="mdi mdi-eye"></i>查看</button>'; //补款升级合同
    }else{
        html += '<button class="btn btn-default" id="detail"><i class="mdi mdi-eye"></i>查看</button>';
    }

    // html += '<button class="btn btn-default" id="detail"><i class="mdi mdi-eye"></i>查看</button>';
    html += '<div class="dropdown" style="margin-right: -10px;">' +
        '         <button class="btn btn-link" data-index="' + index + '">' +
        '             <i class="mdi mdi-dots-vertical"></i>' +
        '         </button>' +
        '         <ul class="dropdown-menu">';
    // html += '<li><a href="#!" id="edit">编辑</a></li>';
    // html += '<li><a href="#!" id="renew" data-toggle="modal" data-target="#addProductModal">续费</a></li>';

    if(row.whetherCheck == '1' && (row.contractStatus == '生效中' || row.contractStatus == '已结束') && (day2 - day1) / (1000 * 60 * 60 * 24)<90){//会员合同

        html += '<li><a href="#!" id="renew" data-toggle="modal" data-target="#addProductModal">续费</a></li>';
    }
    if((row.contractType=='会员单次合同' || row.whetherCheck=='1') && row.contractStatus == '生效中'){
        html += '<li><a href="#!" class="btn-promotion">补款升级</a></li>';
    }
    html += '<li><a href="#!" id="cancel">作废</a></li>';
   // html += '<li><a href="#!" id="addMaterial">补充资料</a></li>';
    return html;
}

/**********************************************************************************************
* 点击续费添加弹框
* */
/*
* data传参
* */
function numberTest(e, preValue) {
    // 移除字符串的空格
    var newVal = $(e.target).val().replace(/\s/g,"");
    if (newVal == '0') {
        promptInfo('数量必须大于等于 1，请重新输入！');
        $(e.target).val(preValue);
        return 'stop';
    }
    if (newVal % 1 !== 0 || newVal < 0 || newVal == '') {
        promptInfo('数量只能为正整数，请重新输入！');
        $(e.target).val(preValue);
        return 'stop';
    }
    if (newVal == preValue) {
        $(e.target).val(preValue);
        return 'stop';
    }
    return newVal;
}

function productQueryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort;                  //排序列名
    params.sortOrder = params.order;                //排序方式
    return params;
}
/*弹框表格原价添加单选按钮*/
var rowsList;
var productFormat = {
    // 产品价格
    priceChose: function (value, row, index, field) {
        if (value == null || value == undefined ) {
            return "-";
        }
        //productUnitPrice

        var type = row.chose || 'productMemberPrice';
        // var type = 'productMemberPrice';
        var html = '';
        if (field == type) {
            html += '<label class="lyear-radio radio-inline radio-primary"><input type="radio" data-target="' + field + '" name="price' + index + '" checked><span>' + value +'</span></label>';
        } else {
            html += '<label class="lyear-radio radio-inline radio-primary"><input type="radio" data-target="' + field + '" name="price' + index + '"><span>' + value +'</span></label>';
        }
        return html;
    },
    // 产品优惠后价格
    discountPrice: function (value, row, index, field) {
        // 优惠价为空 隐藏上传审批图片，否则显示

        // var discountPriceValue = value || '';
        var discountPriceValue;
        value == undefined ? discountPriceValue = '' : discountPriceValue = value;
        if (discountPriceValue != '') {
            discountPriceValue = parseFloat(discountPriceValue);
        }
        var inputId = 'productDiscountPrice' + index;
        var inputHtml = '<input type="text" value="' + discountPriceValue + '" placeholder="请输入" class="form-control" id="' + inputId + '">';
        row.productDiscountPrice = discountPriceValue || $(inputHtml).val();

        return inputHtml;
    },
    // 价格选择操作
    priceCategoryEvent: {
        'change input': function (e, value, row, index) {

            var inputNode = $(e.target)[0];
            row.chose = $(inputNode).data('target');
            productFormat.priceChose(value, row);
            // 修改价格类型后，清空产品优惠后价格
            productFormat.discountPrice('', row);
            productFormat.total(value, row, index, 'productTotal');
            $('#productListTable').bootstrapTable('updateRow', {
                index,
                replace: true,
                row
            });
        }
    },

    // 产品数量
    number: function (value, row, index, field) {
        var numberValue = Number(value) || 1;
        var inputId = 'productNumber' + index;
        var inputHtml = '<input type="text" value="' + numberValue + '" placeholder="请输入" class="form-control" id="' + inputId + '">';
        row.productNumber = numberValue || $(inputHtml).val();

        return inputHtml;
    },
    // 总计
    total: function (value, row, index, field) {
        // 价格默认为产品单价
        // productMemberPrice productUnitPrice
        // var price = row.productMemberPrice;
        var price = row[row.chose] || row.productMemberPrice;
        var rowTotal = price * row.productNumber;
        row.productTotalPrice = rowTotal;

        return rowTotal;
    },
    // 产品优惠后价格
    discountPrice: function (value, row, index, field) {
        // 优惠价为空 隐藏上传审批图片，否则显示
        // value == '' ? $('.approval').hide(0) : $('.approval').show(0);
        // var discountPriceValue = value || '';
        var discountPriceValue;
        value == undefined ? discountPriceValue = '' : discountPriceValue = value;
        if (discountPriceValue != '') {
            discountPriceValue = parseFloat(discountPriceValue);
        }
        var inputId = 'productDiscountPrice' + index;
        var inputHtml = '<input type="text" value="' + discountPriceValue + '" placeholder="请输入" class="form-control" id="' + inputId + '">';
        row.productDiscountPrice = discountPriceValue || $(inputHtml).val();

        return inputHtml;
    },
    // 优惠后价格 自定义事件
    priceEvent: {
        'change input': function (e, value, row, index) {
            // console.log(e, value, row,9999)
            // $(e.target).val() == '' ? $('.approval').hide(0) : $('.approval').show(0);
            var newValue = activityPriceTest(e, value, row);
            console.log(newValue,'newValue',row)
            if (newValue == 'stop') return;

            productFormat.discountPrice(newValue, row);

            $('#productActivityTable').bootstrapTable('updateRow', {
                index,
                replace: true,
                row
            });

            // e.stopPropagation();
        },
        'click input': function (e, value, row, index) {

            e.stopPropagation( )
        }
    },
    numberEvent: {
        'change input': function (e, value, row, index) {
            // 对数值进行判断
            var newValue = numberTest(e, value);
            if (newValue == 'stop') return;

            productFormat.number(newValue, row);
            $('#productActivityTable').bootstrapTable('updateRow', {
                index,
                replace: true,
                row
            });
        },
        'click input': function (e, value, row, index) {

            e.stopPropagation( )
        }
    }
}

/****
 * 被选中check
 * */
var totalAmountData=0,discountAmountData=0,realAmountData=0,receivablesData=0;
var trueList1=false,trueList2=false;
$("#productListTable").on('click',function () {
    // $(this).find('input').attr('disabled',true)
    // console.log($(this),'123321')
    // #productListTable tbody .selected td input{
    //
    // }
    $("#productListTable tbody  td input[type=text]").attr("disabled",false)
    $("#productListTable tbody .selected td input[type=text]").attr("disabled",true)

    rowsList = $('#productListTable').bootstrapTable('getSelections');



    totalAmountData=0,discountAmountData=0,realAmountData=0,receivablesData=0
    commitList(rowsList)

    for(let i=0,len=rowsList.length;i<len;i++){
        if(rowsList[i].productDiscountPrice==''){
            $.alert('报价不能为空！')
            return false;
        }
    }
    // 优惠券按钮开关
    if (rowsList.length == 1) {
        $('#valuationTotal').val(rowsList[0].productDiscountPrice * rowsList[0].productNumber);
        $('#couponTableToolbar button').prop('disabled', false);
    } else {
        $('#valuationTotal').val('');
        $('#couponTableToolbar button').prop('disabled', true);
        $('#couponTable').bootstrapTable('removeAll');
    }

})

function commitList(rowsList) {
    if(rowsList.length==0){
        $('.approval').hide(0);

        $("#totalAmount").html(totalAmountData)

        //    合同优惠总金额

        $("#discountAmount").html(discountAmountData)
        //    合同实际总金额 realAmount
        $("#realAmount").html(realAmountData)
        //    应收款 receivables
        $("#receivables").html(receivablesData)
        return;
    }
    // 计价总计(当前报价*数量)
    var contantMoney=0;
    trueList1=false
    trueList2=false
    for(let i=0,len=rowsList.length;i<len;i++){
        //    合同总金额 totalAmountData
        totalAmountData+=rowsList[i].productMemberPrice* rowsList[i].productNumber
        contantMoney+=rowsList[i].productDiscountPrice* rowsList[i].productNumber
        if(rowsList[i].productDiscountPrice<rowsList[i].productMemberPrice){
            trueList1=true

        }else{
            trueList2=true
        }
    }
    if(trueList2==true && trueList1==false){
        $('.approval').hide(0);
    }else{

        $('.approval').show(0);
    }
    // 优惠券优惠金额
    var couponPrice = couponPriceSum(contantMoney);

    discountAmountData=totalAmountData-contantMoney + couponPrice;
    console.log(totalAmountData, contantMoney, couponPrice)
    console.log(totalAmountData-contantMoney + couponPrice)
    setTimeout(function () {

        //合同总金额
        $("#totalAmount").html(totalAmountData)
        //    合同优惠总金额  // 合同优惠总金额 = 合同总金额 - 产品计价总计 + 优惠券减免额度

        //合同优惠总金额
        if(discountAmountData<0){
            discountAmountData=0
        }
        $("#discountAmount").html(discountAmountData)
        //合同实际总金额
        $("#realAmount").html(contantMoney-couponPrice)
        //应收款
        $("#receivables").html(contantMoney-couponPrice+Number($("#surcharge").val()))

    },100)
}


/**
 * 功能：活动产品列表价格判断
 * */
function activityPriceTest(e, preValue, row) {
    // 移除字符串的空格
    var newVal = $(e.target).val().replace(/\s/g,"");

    if (newVal == '') {
        return '';
    }
    if (newVal == preValue) {
        $(e.target).val(preValue);
        return 'stop';
    }
    if (isNaN(newVal) || newVal < 0) {
        promptInfo("请输入正确的价格！");
        $(e.target).val(preValue);
        return 'stop';
    } else {
        // 判断输入值是否高于活动原价
        if (parseFloat(newVal) > row.activityPrice) {
            promptInfo("活动优惠价不能高于活动原价，请重新输入！");
            $(e.target).val(preValue);
            return 'stop';
        }
    }
    return parseFloat(newVal).toFixed(2);
}
//合同续费点击事件
// 产品列表 - 添加产品弹窗列表
function dataContract(params) {
    var data={
        pageSize: params.limit,                         //页面大小
        pageIndex: (params.offset / params.limit) + 1,   //页码
        sortName: params.sort,      //排序列名
        sortOrder: params.order, //排位命令（desc，asc）
        productCategories: 2, // 会员类型
        whetherRenew : '0'
    }
    return JSON.stringify(data)
}

var contractId='0ec84d10e2a94f749418bd6fa5df2c54'
// 产品列表 - 添加产品弹窗列表
function initList(){
    $('#productListTable').bootstrapTable('destroy');
    // $('#productListTable').bootstrapTable('refresh');
    $('#productListTable').bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        // url: '/customerContract/selectContractRenewalInformation?contractId='+contractId,//请求地址
        url:"/customerMemberProduct/selectContractMemberProductList",
        method: 'post',//请求方式
        contentType:"application/json;charset=utf-8",
        dataType: "json",                   // 数据类型
        striped: true,                      // 是否显示行间隔色
        sortable: true,                     // 是否启用排序
        sortOrder: "desc",                  // 排序方式
        sortName: 'createTm',               // 排序字段
        cache: false,                       // 是否使用缓存
        showColumns: false,                 // 显示隐藏列
        showRefresh: false,                 // 显示刷新按钮
        showToggle: false,                  // 切换显示样式
        showFooter: false,                  // 显示Table脚部
        pagination: true,                   // 是否显示分页
        showPaginationSwitch: false,        // 是否显示分页按钮
        clickToSelect: true,                // 是否启用点击选中行
        maintainSelected: true,             // 分页是否保留选中
        singleSelect: false,
        minimumCountColumns: 2,             // 最少要显示的列数
        undefinedText: '-',                  // cell没有值时显示
        sidePagination: "server",           // 分页方式：client客户端分页，server服务端分页
        uniqueId: 'customerProductId',
        idField: 'customerProductId',
        pageSize: 9999,                        // 每页的记录行数
        pageNumber: 1,                      // 初始化加载第1页，默认第1页
        pageList: "[5, 10, 15, 20]",        // 可供选择的每页的行数

        queryParams: dataContract,//查询参数
        columns: [

            {title: '主键', field: 'customerProductId', visible: false},
            {checkbox: true, visible: true},
            {title: '产品名称', field: 'productName', align: 'left', valign: 'middle'},
            {title: '产品类别', field: 'productCategories', align: 'left', valign: 'middle',visible: false},
            {title: '产品原价', field: 'productOriginalPrice', align: 'left', valign: 'middle'},
            {title: '产品单价', field: 'productUnitPrice', align: 'left', valign: 'middle'},
            {title: '产品会员价', field: 'productMemberPrice', align: 'left', valign: 'middle'},
            {title: '当前报价', field: 'productDiscountPrice', align: 'left', valign: 'middle', width: '160', events: productFormat.priceEvent, formatter: productFormat.discountPrice},
            {title: '产品数量', field: 'productNumber', align: 'left', valign: 'middle', width: '160', events: productFormat.numberEvent, formatter: productFormat.number},
            // {title: '操作', field: 'productOperation', align: 'right', valign: 'middle', width: '100', formatter: productFormat.operation},
            {title: '产品编码', field: 'productCode', visible: false},
        ],
        responseHandler: function (result) {
            if(result.code == "000000") {
                var obj = {
                    // "rows": result.data.productEditArr.list,
                    // "total": result.data.productEditArr.totalRecords//总条数
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };

                // getCustomerContactPersonSelect(result.data.contactId);


            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {

        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                // alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

function initFollowRecord(customerId){
    $.ajax({
        type: 'GET',
        dataType: "json",
        url: '/clueFollow/selectClueFollowListByCustomerId?customerId=' + customerId,
        success: (function (data) {
            if (data.code == "000000") {
                var html = '';
                $.each(data.data, function(n, value) {
/*                    if(contract != null && contract.followRecordId == value.clueFollowId){
                        html += '<option value="' + value.clueFollowId + '" selected>' + value.followWayName + ' ' + value.followTm + '</option>';
                    }else {*/
                        html += '<option value="' + value.clueFollowId + '">' + value.followWayName + ' ' + value.followTm + '</option>';
/*                    }*/
                });
                $('#followRecordList').selectpicker('destroy').html(html).attr('disabled', false).selectpicker('refresh');
            } else {
                alert("跟进记录下拉框-请求失败");
            }
        }),
        error: (function (res) {
            alert("跟进记录下拉框-请求失败");
        })
    });
}

function initOpportunity(customerId){
    $.ajax({
        type: 'GET',
        dataType: "json",
        url: '/opportunity/selectOpportunityListByCustomerId?customerId=' + customerId,
        success: (function (data) {
            if (data.code == "000000") {
                var html = '';
                $.each(data.data, function(n, value) {
/*                    if(contract!=null&&contract.opportunityId == value.opportunityId){
                        html += '<option value="' + value.opportunityId + '" selected>' + value.opportunityTitle + '</option>';
                    }else {*/
                        html += '<option value="' + value.opportunityId + '">' + value.opportunityTitle + '</option>';
/*                    }*/
                });

                $('#opportunityList').selectpicker('destroy').html(html).attr('disabled', false).selectpicker('refresh');

            } else {
                alert("赢单商机下拉框-请求失败");
            }
        }),
        error: (function (res) {
            alert("赢单商机下拉框-请求失败");
        })
    });
}

/**
 *客户联系人下拉加载（先选择客户名称调用）
 */
function getCustomerContactPersonSelect(contract){
    $('#phoneNumber').val('');  // 清空联系人手机号

    //客户id
    var customerId = $('#customerList').val();

    $.ajax({
        type: 'GET',
        dataType: "json",
        url: '/customer/selectContactPersonListByCustomerId?customerId=' + customerIdNum,
        success: (function (data) {
            if (data.code == "000000") {
                var html = '';
                $.each(data.data, function(n, value) {

                    if(contract != null && contract == value.customerContactPersonId) {
                        html += '<option data-phone="' + value.contactInformation + '" value="' + value.customerContactPersonId + '"  selected>' + value.contactName + ' — '+ value.contactInformation +'</option>';
                    }else {
                        html += '<option data-phone="' + value.contactInformation + '" value="' + value.customerContactPersonId + '">' + value.contactName + ' — '+ value.contactInformation +'</option>';
                    }
                    // html += '<option data-phone="' + value.contactInformation + '" value="' + value.customerContactPersonId + '">' + value.contactName + ' — '+ value.contactInformation +'</option>';
                });

                $('#customerContractList').html(html).attr('disabled', false).selectpicker('refresh');
                $('#customerContractList').on('changed.bs.select', function (e, clickedIndex, isSelected, previousValue) {
                    $('#phoneNumber').val($(this).find('option').eq(clickedIndex).data('phone'));
                })
                // if (contract) {
                //     $('#phoneNumber').val($('#customerContractList option:selected').data('phone'));
                // }
                $('#phoneNumber').val($('#customerContractList option:selected').data('phone'));
            } else {
                alert("客户联系人下拉请求失败");
            }
        }),
        error: (function (res) {
            alert("客户联系人下拉请求失败");
        })
    });
}

/**
 * 合同续费保存功能
 */
function addRenewContract(element){
    var $this = $(element);

    //客户id
    var customerId = "";
    //客户名称
    var customerName = "";
    //客户类型
    var customerType = "";
    //客户邮箱
    var customerEmail = "";
/*    //跟进记录id
    var followRecordId = "";
    //商机id
    var opportunityId = "";
    //合作开发人员id
    var coDeveloperList = [];
    //是否保密
    var whetherKeepSecret = "";*/
    //合同原来起始时间
    var contractOldStartDate = "";
    //合同原来结束时间
    var contractOldEndDate = "";

    $.ajax({
        type: 'GET',
        async:false,
        dataType: "json",
        url: '/customerContract/selectContractById?contractId=' + contractId,
        success: (function (data) {
            if (data.code == "000000") {
                customerId = data.data.customerId;
                customerName = data.data.customerName;
                customerType = data.data.customerType;
                customerEmail = data.data.customerEmail;
                //followRecordId = data.data.followRecordId;
                //opportunityId = data.data.opportunityId;
                //coDeveloperList = data.data.coDeveloperList;
                //whetherKeepSecret = data.data.whetherKeepSecret;
                contractOldStartDate = data.data.contractStartDate;
                contractOldEndDate = data.data.contractEndDate;
            } else {
                alert("获取合同信息请求失败");
            }
        }),
        error: (function (res) {
            alert("获取合同信息请求失败");
        })
    });

    //联系人id
    // var contactId=$("#customerContractList").val();
    var contactId = '';
    //联系人名称
    var contactName = $.trim($('#customerContractName').val());
    //联系方式
    var contactDetails = $.trim($('#customerContactInformation').val());
    //会员主合同
    var masterMembershipContract = contractId;
    //合同起止日期
    var contractPeriodValidity = $("#contractDate").val().split('至');
    // 起止时间-开始时间
    var contractNewStartDate = $.trim(contractPeriodValidity[0]);
    // 起止时间-结束时间
    var contractNewEndDate = $.trim(contractPeriodValidity[1]);
    //付款账号
    //var paymentAccount = $('#paymentAccount').val();
    //支付方式
    var paymentMethod = $('#paymentMethod').val();
    //附加费用
    //金额
    var orderSurcharge = $('#surcharge').val();
    //备注
    var orderSurchargeRemark = $('#orderSurchargeRemark').val();
    //是否加盖公章
    var applyElectronicContract=$('input[name="applyElectronicContract"]:checked').val();


    //合同实际总金额
    var contractActualTotalAmount = $("#realAmount").text();
    //合同优惠总金额
    var contractDiscountTotalAmount = $("#discountAmount").text();
    //合同 总金额
    var contractTotalAmount = $("#totalAmount").text();
    //应收款
    var contractReceivables= $("#receivables").text();

    // 上传审核图片
    /*    var examineFile = $('#examineImg');

        // 合同优惠时，必须上传审核图片
        if(contractDiscountTotalAmount != 0 && !$('#examinedPic').val()){
            if (examineFile.val()) {
                uploadImg(examineFile);
            } else {
                promptInfo("审核为必填项!");
                return;
            }
        }
    */

    //关联跟进记录
    var followRecordId = $('#followRecordList').val();
    //关联赢单商机
    var opportunityId = $('#opportunityList').val();

    //合同附件
    var contractAnnexId = $('#contractPic').val();
    //合同审核
    var reviewAnnexId = $('#examinedPic').val();

    //审核备注
    var contractReviewNotes = $('#contractReviewNotes').val();

    // 续费列表数据
    //获取选中行的数据
    var productData = $('#productListTable').bootstrapTable('getSelections');
    // var productData = $('#productListTable').bootstrapTable('getData', true);        // 产品列表数据
    var productArr = [];                                                            // 产品列表数组
    for (var i = 0; i < productData.length; i++) {
        if(productData[i].productDiscountPrice==''){
            promptInfo("当前报价不能为空!");
            return;
        }
        var rowData = {
            productId: productData[i].customerProductId,                            // 产品id
            productName: productData[i].productName,                                // 产品名称
            productCategories: productData[i].productCategories,                    // 产品分类--0:非会员;1:会员；
            productOriginalPrice: productData[i].productOriginalPrice,              // 原价
            productUnitPrice: productData[i].productUnitPrice,                      // 单价
            productMemberPrice: productData[i].productMemberPrice,                  // 会员价
            productFinalPrice: productData[i].productDiscountPrice,                 // 成交价
            productTotalPrice: productData[i].productTotalPrice,                    // 总计价格
            productQuantity: productData[i].productNumber,                          // 数量
            productCode:productData[i].productCode,                                 // 产品编码
        }
        productArr.push(rowData);
    }

    // 优惠券数据
    var couponTableData = $('#couponTable').bootstrapTable('getData', true);
    var couponData = [];
    if (couponTableData.length) {
        for (let i = 0; i < couponTableData.length; i++) {
            var couponList = {};
            couponList.chsCustomerCouponId = couponTableData[i].chsCustomerCouponId;
            couponList.receiveCouponId = couponTableData[i].receiveCouponId;
            couponList.couponName = couponTableData[i].couponName;
            couponList.couponType = couponTableData[i].couponType;
            couponList.couponQuota = couponTableData[i].couponQuota;
            couponList.couponDiscount = couponTableData[i].couponDiscount;
            couponData.push(couponList);
        }
    } else {
        couponData = null;
    }

    //合作开发人员
    var coDeveloperList = $('#cooperateTable').bootstrapTable('getData', true);


    //产品判空提示
    if(productArr.length==0){
        promptInfo("产品不能为空!");
        return;
    }


    //客户联系人判空提示
    if (!contactName) {
        promptInfo("客户联系人不能为空!");
        return;
    }

    //联系方式判空提示
    /*if (!contactDetails) {
        promptInfo("联系方式不能为空!");
        return;
    }*/

    // 联系方式判断
    var contactInformationReg = /^(\d{1,20})$/;
    var contactInformationPattern = new RegExp(contactInformationReg);
    if(!contactDetails){
        promptInfo("联系方式不能为空！");
        return;
    }else{
        if(!contactInformationPattern.test(contactDetails)) {
            promptInfo("请输入正确的手机号");
            return;
        }
    }




    //客户邮箱判空提示
    // if (!customerEmail) {
    //     promptInfo("客户邮箱不能为空!");
    //     return;
    // }

    //合同起止日期判空提示
    if (!contractNewStartDate) {
        promptInfo("合同起止日期不能为空!");
        return;
    } else {
        var dateArr = $('#contractDate').val().split(' 至 ');
        var dateReg = /((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29))/;
        // 日期格式验证(至两侧空格不能省略)
        if (dateArr[0].length > 10) {
            promptInfo('修改的合同起止日期格式不正确，请重新选择或输入正确的日期格式(YYYY-MM-DD 至 YYYY-MM-DD)');
            return;
        }
        // 验证开始日期格式
        if (!dateReg.test(dateArr[0])) {
            promptInfo('合同开始日期格式不正确，请选择或输入正确的日期格式(YYYY-MM-DD)');
            return;
        }
        // 验证结束日期格式
        if (!dateReg.test(dateArr[1])) {
            promptInfo('合同结束日期格式不正确，请选择或输入正确的日期格式(YYYY-MM-DD)');
            return;
        }
        // 验证结束日期是否大于开始日期
        if (moment(dateArr[1]).isBefore(dateArr[0])) {
            promptInfo('合同结束日期不能早于开始日期，请选择或输入正确的起止日期(YYYY-MM-DD 至 YYYY-MM-DD)');
            return;
        }
    }

    //支付方式判空提示
    if (!paymentMethod) {
        promptInfo("支付方式不能为空!");
        return;
    }

    // 合同附件判空提示
    /*if (!contractAnnexId) {
        // 上传合同附件
        var contractFile = $('#contractImg');
        // 合同附件不为空上传图片并返回图片id
        if (contractFile.val()) {
            contractAnnexId = uploadImg(contractFile);
        } else {
            promptInfo("合同附件必须上传!");
            return;
        }
    }*/

    //商机判空提示
    if (!opportunityId) {
        promptInfo("关联赢单商机必选!");
        return;
    }

    //跟进记录判空提示
    if (!followRecordId) {
        promptInfo("跟进记录必选!");
        return;
    }

    // 审核附件判空提示
    /*if(contractDiscountTotalAmount!=0&&!reviewAnnexId){
        promptInfo("审核附件必须上传!");
        return;
    }*/

    //审核备注判空提示
    /*if(contractDiscountTotalAmount!=0&&!contractReviewNotes){
        promptInfo("审核备注必填!");
        return;
    }*/

    // 验证合作开发人员分配金额
    for (let i = 0; i < coDeveloperList.length; i++) {
        if (coDeveloperList[i].allocationMount == '') {
            $.alert({
                title: '温馨提示',
                content: '合作开发人员分配金额不能为空，请输入！',
                scrollToPreviousElement: false,
                scrollToPreviousElementAnimate: false,
                buttons: {
                    confirm: {
                        text: '确认',
                        btnClass: 'btn-primary',
                        action: function () {
                            // e.preventDefault();
                            $('#allOcation-' + i).focus();
                            return;
                        }
                    }
                }
            });
            return;
        }
    }

    var jsonData = {
       "contractType":'4',
       "customerId":customerId,
       "customerName":customerName,
       "customerType":customerType,
       "contactId":contactId,
       "contactName":contactName,
       "contactDetails":contactDetails,
        "customerEmail":customerEmail,
       "masterMembershipContract":masterMembershipContract,
        "contractNewStartDate":contractNewStartDate,
       "contractNewEndDate":contractNewEndDate,
        //"paymentAccount":paymentAccount,
        "paymentMethod":paymentMethod,
        "followRecordId":followRecordId,
        "opportunityId":opportunityId,
        "applyElectronicContract":applyElectronicContract,
        //"whetherKeepSecret":whetherKeepSecret,
        "contractOldStartDate":contractOldStartDate,
        "contractOldEndDate":contractOldEndDate,
        "contractTotalAmount":contractTotalAmount,
        "contractDiscountTotalAmount":contractDiscountTotalAmount,
        "contractActualTotalAmount":contractActualTotalAmount,
        "contractReceivables":contractReceivables,
        "contractReviewNotes":contractReviewNotes,
        //附加费用
        "orderSurcharge":orderSurcharge,
        "orderSurchargeRemark":orderSurchargeRemark,
        "contractAnnexId":contractAnnexId,
        "reviewAnnexId":reviewAnnexId,
        "customerContractProductAddQOList":productArr,
        "coDeveloperList":coDeveloperList,
        // 优惠券
        "contractCouponQOList": couponData,
    }
    console.log(jsonData);

    $this.prop('disabled', true).addClass('btn-label').html('<label><i class="mdi mdi-loading mdi-spin"></i></label>创建中...');

    $.ajax({
        url: '/customerContract/addContractInformation',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if(data.code == '000000'){
                $.alert({
                    title: '提示',
                    content: '保存成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                //刷新列表
                                $customerContractTable.bootstrapTable('refresh')
                                //关闭弹框
                                $('#addProductModal').modal('hide');
                            }
                        }
                    }
                });
            } else if(data.code == 'CV0001'){
                //合同不能编辑
                $.alert(data.message);
            } else if(data.code == 'CV0002'){
                //没有会员产品合同不能保存
                $.alert(data.message);
            }else {
                $.alert("保存失败");
            }
        }),
        error: (function (res) {
            $.alert("保存失败");
        }),
        complete: function () {
            $this.prop('disabled', false).removeClass('btn-label').html('确定');
        }
    })
}

function promptInfo(content, callBack) {
    $.alert({
        title: '温馨提示',
        content: content,
        scrollToPreviousElement: false,
        scrollToPreviousElementAnimate: false,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: callBack
            }
        }
    });
}

//uploadImg fileSelected
var $fileUpLoad=$("#contractImg")
function uploadImg(type) {

    if(type=='contractImg'){
        $fileUpLoad=$("#contractImg")
    }else{
        $fileUpLoad=$("#examineImgBox")
    }
    let fileToUpLoad=$fileUpLoad.prop('files')[0]
    var formFile = new FormData();
    formFile.append("file", fileToUpLoad);
    var data = formFile;
    var imgId;
    $.ajax({
        url: '/file/uploadByOneFile',
        data: data,
        type: "POST",
        dataType: "json",
        async: false,
        cache: false,
        processData: false,
        contentType: false,
        success: function (data) {
            if (data.code == "000000") {
                $fileUpLoad.prev().val(data.data.fileId)
                // obj.next('input.image-id').val(data.data.fileId)

                imgId = data.data.fileId;
            } else {
            }
        },
        error: (function (res) {
            $.alert(res);
        })
    });
    return imgId;
}

/**
 * 合同列表--自定义操作列事件
 */
window.operateEvents = {
    // paydetail 补款升级详情
    'click #paydetail': function (e, value, row, index) {
        parent.$(parent.document).data('multitabs').create({
            iframe : true,
            title : '合同详情',
            //?contractId=" + row.contractId + "&urlType=1"
            url : "/front/contractManager/contractDetailPayment?contractId=" + row.contractId
        }, true);
    },
    //合同查看点击事件
    'click #detail': function (e, value, row, index) {
        parent.$(parent.document).data('multitabs').create({
            iframe : true,
            title : '合同详情',
            url : "/front/contractManager/contractDetail?contractId=" + row.contractId + "&urlType=1"
            //url : "/front/contractManager/contractDetail?contractId=" + row.contractId
        }, true);
    },
    // 补款升级
    'click .btn-promotion': function (e, value, row, index) {
        parent.$(parent.document).data('multitabs').create({
            iframe : true,
            title : '补款升级',
            url : "/front/contractManager/contractPromotion?contractId=" + row.contractId + '&productOrderId=' + row.orderId + '&customerId=' + row.customerId + '&contractType=' + row.contractType
        }, true);
    },
    //合同作废
    'click #cancel': function (e, value, row, index) {
        if(row.contractStatus == "未生效"&row.paymentStatus == "0"){
            $.alert({
                title: '提示',
                content: "确定要作废吗？",
                buttons: {
                    confirm: {
                        text: '确认',
                        btnClass: 'btn-primary',
                        action: function () {
                            $.ajax({
                                type: "post",
                                url: "/customerContract/cancelCustomerContract",
                                data: {
                                    contractId: row.contractId,
                                    contractStatus: "4"
                                },
                                dataType: 'json',
                                success: function (data, status) {
                                    if (data.code == '000000') {
                                        $.alert('操作成功!');
                                        $customerContractTable.bootstrapTable('refreshOptions', {pageNumber: 1});
                                    } else {
                                        $.alert(data.message);
                                    }
                                },
                                error: function () {
                                    $.alert('修改失败，请稍后再试!');
                                }
                            });
                        }
                    },
                    cancel: {
                        text: '取消',
                        action: function () {
                        }
                    }
                }
            })
        }else{
            $.alert("只有未生效且未回款的合同才能作废");
        }
    },
    //合同查看点击事件
    'click #edit': function (e, value, row, index) {
        parent.$(parent.document).data('multitabs').create({
            iframe : true,
            title : '编辑合同详情',
            url : "/front/contractManager/userAddContract?contractId=" + row.contractId
        }, true);
    },
    //合同续费点击事件
    'click #renew': function (e, value, row, index) {
        contractId=row.contractId
        customerIdNum=row.customerId
        initList()

        //初始化商机和跟进记录
        initFollowRecord(customerIdNum)
        //初始化商机
        initOpportunity(customerIdNum)

        // 初始化优惠券列表
        selectCouponTable();
    },
/*    //补充资料点击事件
    'click #addMaterial': function (e, value, row, index) {

    },*/
};

//合同列表--全部、会员产品合同、非会员产品合同tab切换
function changeTab(tabStr){
    //清空搜索条件
    clearSearchData();
    if (tabStr == 'all') {
        $('#tabNumber').val(2);//全部
        $(".member-show").hide()
    }

    if(tabStr == 'member') {
        $('#tabNumber').val(1);//会员产品合同
        $(".member-show").show()
    }

    if (tabStr == 'noMember') {
        $('#tabNumber').val(0);//非会员产品合同
        $(".member-show").hide()
    }
    $('#filterContent').collapse('hide');//收起高级筛选
    $customerContractTable.bootstrapTable('refreshOptions', {pageNumber: 1,queryParams: queryParams});

}

//清空搜索条件、重置查询条件
function clearSearchData(){
    resetBanner();
    $('.filter-content input').val('');//清空--高级筛选input框
    $('.filter-content select').val('').selectpicker('refresh');//清空--高级筛选select框
    $('.selector-box dd').find('a').removeClass("active")
    $('.selector-box dl').find("dt").next().find('a').addClass("active")
}

//重置审核类型、回款状态、合同类型(会员产品合同有)、全部/上月/本周/本月/本年
function resetBanner(){
    $('.all').addClass('active-second');//全部
    $('.lastMonth').removeClass('active-second');//上月
    $('.month').removeClass('active-second');//本周
    $('.week').removeClass('active-second');//本月
    $('.year').removeClass('active-second');//本年
    $("#dateType").val("all");
    //审核类型单选重置为全部
    $('#reviewStatusAll').prop('checked',true);
    //回款状态置单选为全部
    $('#paymentStatusAll').prop('checked',true);
    //清空合同创建日期起始日期、结束日期
    $('.create-time').val('');
    //合同状态
}

/**
 * 审核状态的单选按钮点击
 */
$(".form-review-status").on('click',function () {
    $customerContractTable.bootstrapTable('refreshOptions', {pageNumber: 1,queryParams: advancedQueryParams});
});

/**
 * 回款状态的单选按钮点击
 */
$(".form-payment-status").on('click',function () {
    $customerContractTable.bootstrapTable('refreshOptions', {pageNumber: 1,queryParams: advancedQueryParams});
});

/**
 * 合同类型的单选按钮点击(会员产品合同有)
 */
$(".form-contract-type").on('click',function () {
    $customerContractTable.bootstrapTable('refreshOptions', {pageNumber: 1,queryParams: advancedQueryParams});
});


/**
 * 全部/周/月/年切换
 * @param time
 */
function selectTime(time) {
    if (time == 'all') {//全部
        $('.all').addClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.lastMonth').removeClass('active-second');
        $("#dateType").val("all");
    }
    if (time == 'lastMonth') {//上月
        $('.lastMonth').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#dateType").val("lastMonth");
    }
    if (time == 'year') {//本年
        $('.year').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.lastMonth').removeClass('active-second');
        $("#dateType").val("thisYear");
    }
    if (time == 'month') {//本月
        $('.month').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.lastMonth').removeClass('active-second');
        $("#dateType").val("thisMonth");
    }
    if (time == 'week') {//本周
        $('.week').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.lastMonth').removeClass('active-second');
        $("#dateType").val("thisWeek");
    }
    // if(time == 'all'){
    //     $('.create-time').attr('disabled',false);
    // }else{
    //     $('.create-time').attr('disabled',true)
    // }
    $('.create-time').val('');
    $customerContractTable.bootstrapTable('refreshOptions', {pageNumber: 1,queryParams: advancedQueryParams});
}

/*
* 更多列
* */
function hideOrShowColumn(columnName,status) {
    if (status.checked){
        $customerContractTable.bootstrapTable('showColumn', columnName);
        $customerContractTable.bootstrapTable('refresh')
    }else{
        $customerContractTable.bootstrapTable('hideColumn', columnName);
        $customerContractTable.bootstrapTable('refresh')
    }
    //contractStatusMultiple
    $customerContractTable.find('th[data-field="contractStatus"]').append(htmlIcon)
    setTimeout(function () {
        let cssLeftX=$(".css-mdi").offset().left-10+'px';
        let cssLeftY=$(".css-mdi").offset().top-10+'px';
        $(".select-absolute").css({position:"fixed",left: cssLeftX,top:cssLeftY})
    },100)
}

/*
* 合同状态 change事件 contractStatusSelect
* */
$("#contractStatusSelectMultiple").on('change',function () {
    $customerContractTable.bootstrapTable('refreshOptions', {pageNumber: 1,queryParams: advancedQueryParams});
});

//点击审核状态
$('.selector-box dd').on('click', function () {
    $(this).find('a').addClass('active')
    $(this).siblings().find('a').removeClass('active')

});

$(document).scroll(function () {
    let cssLeftX=$(".css-mdi").offset().left+'px';
    let cssLeftY=$(".css-mdi").offset().top+'px';
    var  sTop = document.body.scrollTop;
    $(".select-absolute").css({position:"fixed",left: cssLeftX,top:$(".css-mdi").offset().top-$(window).scrollTop()+'px'})
})

//显示导入线索模态框
function showImportContractModal(){
    $('#importContractModal').modal('show');
}

//取消导入线索模态框
function cancelImportContractList() {
    $("#importContractFile").val("");
}

//导入线索名单
function importContractList() {
    if(!document.getElementById('importContractFile').files[0]){
        $.alert({
            title: '温馨提示',
            content: '请选择文件！',
        });
        return;
    }
    var fileName = document.getElementById('importContractFile').files[0].name;
    var fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length);
    var formData = new FormData();
    //接口接收参数 键值形式 添加到formData中
    formData.append("file",$("#importContractFile")[0].files[0]);
    if(fileName!="" && (fileType.toLocaleUpperCase()==".XLSX"||fileType.toLocaleUpperCase()==".XLS")){
        $.ajax({
            url: '/contract/contractImport',
            type: 'POST',
            dataType:"json",
            contentType:false,
            data: formData,
            processData: false,
            success:(function(data) {
                if(data.code == "000000"){
                    var importContractNum = data.data.importContractNum;
                    var customerEmptyIdList = data.data.customerEmptyIdList;
                    var customerNotExistIdList = data.data.customerNotExistIdList;
                    var repeatIdList = data.data.repeatIdList;
                    var ownerEmptyIdList = data.data.ownerEmptyIdList;
                    var importFailIdList = data.data.importFailIdList;
                    var notValidIdList = data.data.notValidIdList;

                    //返回内容
                    var content = "";

                    //导入数量大于0
                    content = "成功导入"+importContractNum+"条数据";
                    //客户为空
                    if(customerEmptyIdList!=""){
                        content = content + "<br>第：" + customerEmptyIdList + "行数据库客户为空，导入失败";
                    }
                    //客户不存在
                    if(customerNotExistIdList!=""){
                        content = content + "<br>第：" + customerNotExistIdList + "行数据客户不存在，导入失败";
                    }
                    //合同已存在
                    if(repeatIdList!=""){
                        content = content + "<br>第：" + repeatIdList + "行数据合同编号已存在，导入失败";
                    }
                    //未生效合同不能导入
                    if(notValidIdList!=""){
                        content = content + "<br>第：" + notValidIdList + "行数据合同状态没有生效中，导入失败";
                    }
                    //所有人不存在不能导入
                    if(ownerEmptyIdList!=""){
                        content = content + "<br>第：" + ownerEmptyIdList + "行数据所有人不存在，导入失败";
                    }
                    //导入失败
                    if(importFailIdList!=""){
                        content = content + "<br>第：" + importFailIdList + "行数据合同导入失败";
                    }


                    $.alert({
                        title: '提示',
                        content: content,
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    $("#importContractFile").val("");
                                    $customerContractTable.bootstrapTable('refresh');
                                }
                            }
                        }
                    });
                    $('#importContractModal').modal('hide');
                    $("#importContractFile").val("");
                }else if(data.code == "CI0001"){
                    $.alert({
                        title: '提示',
                        content: data.message,
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    $("#importContractFile").val("");
                                }
                            }
                        }
                    });
                }else{
                    $.alert("导入失败");
                    $("#importContractFile").val("");
                }
            }),
            error:(function() {
                $.alert("导入出错！");
                $("#importContractFile").val("");
            })
        });
    } else {
        $.alert({
            title: '温馨提示',
            content: '请上传.xlsx或.xls文件！',
        });
    }
}

/**
 * 下载模板
 */
function downContractTemplate(){
    var url="/contract/downloadContractTemplate";
    window.location.href=encodeURI(encodeURI(url));
}

/* ==================================================== 新增优惠券 ==================================================== */
/**
 * 功能：优惠券已选列表
 * */
function selectCouponTable() {
    $('#couponTable').bootstrapTable('destroy');
    $('#couponTable').bootstrapTable({
        class: 'table table-bordered table-hover table-striped',
        striped: true,          // 是否显示行间隔色
        sortable: true,         // 是否启用排序
        pagination: false,      // 是否显示分页
        undefinedText: '-',     // cell没有值时显示
        uniqueId: 'chsCustomerCouponId',
        columns: [
            {title: '主键', field: 'chsCustomerCouponId', visible: false},
            {title: '优惠券名称',field: 'couponName', align: 'left', valign: 'middle'},
            {title: '优惠券类型', field: 'couponType',align: 'left', valign: 'middle', formatter: couponFormat.couponType},
            {title: '优惠券额度', field: 'couponQuota',align: 'left', valign: 'middle',
                formatter: function (value, row, index) {
                    return value == '0' ? undefined : value;
                }
            },
            {title: '优惠券优惠折扣', field: 'couponDiscount',align: 'left', valign: 'middle',
                formatter: function (value, row, index) {
                    return value == '0' ? undefined : value;
                }
            },
            {title: '操作', field: 'giftOperate', align: 'right', valign: 'middle', formatter: couponFormat.operation},
        ],
        onPostBody: function (data) {
            totalAmountData=0,discountAmountData=0,realAmountData=0,receivablesData=0
            commitList(rowsList);
        },
    });
}
/**
 * 功能：优惠券弹窗列表
 * */
function couponTable(columnsFlag, type) {
    var choseType = type || 'radio';
    $('#couponListTable').bootstrapTable('destroy');
    $('#couponListTable').bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/coupon/selectAvailableCouponPageList',           // 请求地址
        method: 'post',                                         // 请求方式
        contentType: "application/json;charset=UTF-8",          // 请求内容类型
        dataType: "json",                                       // 数据类型
        striped: true,                                          // 是否显示行间隔色
        sortable: true,                                         // 是否启用排序
        sortOrder: "desc",                                      // 排序方式
        sortName: 'createTm',                                   // 排序字段
        cache: false,                                           // 是否使用缓存
        showColumns: false,                                     // 显示隐藏列
        showRefresh: false,                                     // 显示刷新按钮
        showToggle: false,                                      // 切换显示样式
        showFooter: false,                                      // 显示Table脚部
        pagination: true,                                       // 是否显示分页
        showPaginationSwitch: false,                            // 是否显示分页按钮
        clickToSelect: true,                                    // 是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,                                 // 最少要显示的列数
        undefinedText: '-',                                     // cell没有值时显示
        sidePagination: "server",                               // 分页方式：client客户端分页，server服务端分页
        uniqueId: 'receiveCouponId',
        idField: 'receiveCouponId',
        pageSize: 5,                                            // 每页的记录行数
        pageNumber: 1,                                          // 初始化加载第1页，默认第1页
        pageList: "[5, 10, 15, 20]",                            // 可供选择的每页的行数
        // maintainMetaData: true,
        maintainSelected :true,

        serverSelected: !columnsFlag,                           // 开启后端分页记住已选项功能
        serverSelectedField: "receiveCouponId",                 // 已选项的唯一识别主键

        queryParams: couponQueryParams,                         //查询参数
        columns: [
            {title: '主键', field: 'receiveCouponId', visible: false},
            {[choseType]: true, visible: true, width: 40},
            {title: '优惠券名称',field: 'couponName', align: 'left', valign: 'middle'},
            {title: '优惠券类型', field: 'couponType',align: 'left', valign: 'middle', formatter: couponFormat.couponType},
            {title: '优惠券额度', field: 'couponQuota',align: 'left', valign: 'middle', visible: !columnsFlag,
                formatter: function (value, row, index, field) {
                    return row.couponType == '1' ? '' : value;
                }
            },
            {title: '优惠券优惠折扣', field: 'couponDiscount',align: 'left', valign: 'middle', visible: columnsFlag,
                formatter: function (value, row, index, field) {
                    return row.couponType == '1' ? value : '';
                }
            },
            {title: '是否可叠加', field: 'useType', align: 'left', valign: 'middle', visible: !columnsFlag,
                formatter: function (value, row, index, field) {
                    return value == '0' ? '<span class="label label-success">可叠加</span>' : '<span class="label label-warning">不可叠加</span>';
                }
            },
        ],
        responseHandler: function (result) {
            if(result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function (data) {
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
        onCheck: function(row, $element) {
            var selectedRow;
            if ($('#couponCategories input:checked').val() == '1') {
                selectedRow = $('#couponListTable').bootstrapTable('getSelections');
            } else {
                selectedRow = $('#couponListTable').bootstrapTable('getServerSelected', true);
            }

            if (selectedRow.length > 1) {
                // 第一个选择的优惠券类型
                var firstChosedType = selectedRow[0].useType;   // 0-可叠加 1-不可叠加
                // 当前选择优惠券类型
                var thisChosedType = row.useType;

                if (firstChosedType == '1' || (firstChosedType == '0' && thisChosedType == '1')) {
                    console.log('不可叠加');
                    promptInfo('不可叠加优惠券不能和其他优惠券同时使用！', function () {
                        $element.trigger('click');
                    })
                }
            }
        },
        onPostBody: function () {
            $('#couponListTable th.bs-checkbox .lyear-checkbox').hide();
        }
    });
}

/**
 * 添加优惠券弹窗查询条件
 */
function couponQueryParams(params){
    var productListArr = [];
    var productDatas = $('#productListTable').bootstrapTable('getSelections');
    for (let i = 0; i < productDatas.length; i++) {
        productListArr.push(productDatas[i].customerProductId);
    }
    var data = {
        pageSize : params.limit,
        pageIndex : (params.offset / params.limit) + 1,

        customerId: customerIdNum,                                          // 客户id
        productList: productListArr,                                        // 产品idList
        productTotalPrice: Number($('#valuationTotal').val()),              // 产品总价格
        couponType: $('input[name="couponCategories"]:checked').val(),      // 优惠券类型：1-折扣类 2-额度类
        couponName: $.trim($('#searchCouponName').val()),                   // 优惠券名称
    }
    return JSON.stringify(data);
}

/**
 * 优惠券列表 - 自定义内容
 * */
var couponFormat = {
    couponType: function (value, row, index, field) {
        if (value == '1') {
            return '折扣类'
        } else {
            return '额度类'
        }
    },
    operation: function (value, row, index, field) {
        return '<button type="button" class="btn btn-default btn-danger" onclick="removeCouponRow(this, \'' + row.chsCustomerCouponId + '\')"><i class="mdi mdi-delete"></i>删除</button>';
    }
}

/**
 * 功能：添加行
 * 参数：originalTableId - 原表格id  targetTableId - 目标表格id
 * */
function addRow(originalTableId, targetTableId) {
    // 优惠券判断
    if (originalTableId == 'couponListTable') {
        var couponList = $('#couponTable').bootstrapTable('getData', true);
        if (couponList.length) {
            $('#couponTable').bootstrapTable('removeAll');
        }
    }

    var $originalTable;
    var selectRowData;
    var $targetTable = $('#' + targetTableId);
    var targetTabelDate = $targetTable.bootstrapTable('getData', true);


    if (typeof originalTableId == 'object') {
        selectRowData = originalTableId;
    } else {
        $originalTable = $('#' + originalTableId);
        // selectRowData = $originalTable.bootstrapTable('getSelections');
        if (originalTableId == 'couponListTable') {
            // 优惠券
            // selectRowData = $originalTable.bootstrapTable('getSelections');
            if ($('#couponCategories input:checked').val() == '1') {
                selectRowData = $originalTable.bootstrapTable('getSelections');
            } else {
                selectRowData = $originalTable.bootstrapTable('getServerSelected', true);
            }
        } else {
            selectRowData = $originalTable.bootstrapTable("getServerSelected", true);
        }
    }

    if (selectRowData.length == 0) {
        // 弹窗表格未选择时直接关闭弹窗
        $originalTable.parents('.modal').modal('hide');
        return;
    }

    var targetId;
    var priceField;
    var numberField;

    if (!!selectRowData[0].customerProductId) {
        // 产品列表字段
        targetId = 'customerProductId';
        priceField = 'productDiscountPrice';
        numberField = 'productNumber';
    }
    if (!!selectRowData[0].productActivityId) {
        // 活动产品列表字段
        targetId = 'productActivityId';
        priceField = 'activityDiscountPrice';
        numberField = 'activityNumber';
    }
    if (!!selectRowData[0].giftActivityName) {
        // 赠品列表字段
        targetId = 'giftActivityName';
        numberField = 'giftActivity';
    }
    if (typeof originalTableId == 'object') {
        targetId = 'productGiftActivityId';
    }
    // console.log(selectRowData);
    if (targetTabelDate.length == 0 ) {
        for (var i = 0; i < selectRowData.length; i++) {
            selectRowData[i][priceField] = '';
            selectRowData[i][numberField] = 1;
            // productMemberPrice[i].chose=
        }
        // 目标表格为空时直接插入行
        $targetTable.bootstrapTable('append', selectRowData);
    } else {
        var targetTableDateStr =  JSON.stringify(targetTabelDate);
        // 目标表格不为空判断是否已存在于表格中
        for (var i = 0; i < selectRowData.length; i++) {
            var str = '"' + targetId + '":"' + selectRowData[i][targetId] + '"';
            if (targetTableDateStr.indexOf(str) != -1) {
                lightyear.notify('所添加产品(' + selectRowData[i].productName + ')已存在，不能重复添加。', 'warning', 1200, '', 'top', 'right');
            } else {
                selectRowData[i][priceField] = '';
                selectRowData[i][numberField] = 1;
                // selectRowData[i].chose=selectRowData[i]
                $targetTable.bootstrapTable('append', selectRowData[i]);
            }
        }
    }
    if (typeof originalTableId == 'string') {
        $originalTable.parents('.modal').modal('hide');
    }
    // var productData = $('#productTable').bootstrapTable('getData', true);
}

/**
 * 功能：删除行
 * 参数：fieldId - 删除行的目标列字段名称  value - 目标字段值
 * */
function removeCouponRow(_this, fieldId, value) {
    $(_this).parents('table').bootstrapTable('removeByUniqueId', fieldId);
}

/**
 * 计算优惠券优惠额度
 * 参数：finalPrice - 计价总计(当前报价*数量)
 * */
function couponPriceSum(finalPrice) {
    var couponPrece = 0;
    var couponDatas = $('#couponTable').bootstrapTable('getData',false);
    for (let i = 0; i < couponDatas.length; i++) {
        if (couponDatas[0].couponType == 2) {
            couponPrece += Number(couponDatas[i].couponQuota);
        } else {
            couponPrece = finalPrice * (100 - couponDatas[i].couponDiscount * 100) / 100;
        }
    }
    return couponPrece;
}